Popular Searches
Popular Course Categories
Popular Courses

Full-Page Screenshots

Full-Page Screenshots

Screenshots & Reporting

Full-Page Screenshots in Selenium

Full-Page Screenshot is a Selenium automation technique used to capture an image of an entire web page instead of capturing only the currently visible browser viewport. A normal screenshot generally captures the visible portion of the browser window, while a full-page screenshot can include content that is below the current viewport.

Full-page screenshots are extremely useful in Selenium automation for documenting complete web pages, capturing failed test evidence, validating long pages, debugging layout problems, recording application states, and attaching visual evidence to automation reports.

In real-world Selenium frameworks, screenshots are commonly integrated with TestNG, JUnit, PyTest, Page Object Model, reporting tools, CI/CD pipelines, and failure-handling utilities.

Course Resource: Selenium Training | Register for Course Demo


1. What is a Full-Page Screenshot?

A full-page screenshot captures the complete webpage, including content that is outside the currently visible browser viewport.

For example, consider a webpage containing:

  • Header
  • Navigation menu
  • Hero section
  • Product sections
  • Forms
  • Tables
  • Footer

If the page is taller than the browser viewport, a normal screenshot may capture only the currently visible section. A full-page screenshot attempts to capture the complete page in a single image.

Browser Viewport

+-----------------------------+

| Header                      |

| Navigation                  |

| Product Section             |

|                             |

| Visible Content             |

+-----------------------------+

 

Full-Page Screenshot

+-----------------------------+

| Header                      |

| Navigation                  |

| Product Section             |

| Product Details             |

| Reviews                     |

| Recommendations             |

| Footer                      |

+-----------------------------+


2. Normal Screenshot vs Full-Page Screenshot

FeatureNormal ScreenshotFull-Page Screenshot
Captured AreaUsually visible viewportEntire page or full document area
Long PageDoes not normally capture everythingDesigned to capture content beyond viewport
Scrolling RequiredUsually noImplementation-dependent
DebuggingShows current screen stateShows broader page state
File SizeUsually smallerUsually larger
Use CaseFailure evidence and visible UIComplete-page documentation and visual analysis


3. Why are Full-Page Screenshots Important?

Modern web applications often contain pages that are much longer than the browser viewport. Capturing only the visible area may not provide enough information when investigating a test failure.

  • Provides complete visual evidence.
  • Helps debug long webpages.
  • Captures content below the fold.
  • Useful for regression testing.
  • Helps document application states.
  • Can be attached to test reports.
  • Useful for failed test analysis.
  • Helps identify layout problems.
  • Can capture long forms and tables.
  • Useful in CI/CD automation.
  • Supports visual testing workflows.


4. Full-Page Screenshot Flow

Start Test

    |

    v

Open Web Application

    |

    v

Load Complete Page

    |

    v

Wait for Page Content

    |

    v

Identify Screenshot Method

    |

    +----------------------+

    |                      |

    v                      v

Native Full Page       Custom Capture

Screenshot             / Scroll Stitching

    |                      |

    +----------+-----------+

               |

               v

        Capture Screenshot

               |

               v

        Save Image File

               |

               v

        Attach to Report

               |

               v

          Test Complete


5. Selenium Screenshot Interface

Selenium provides screenshot functionality through the TakesScreenshot interface. The basic screenshot mechanism captures the current browser screenshot.

import org.openqa.selenium.OutputType;

import org.openqa.selenium.TakesScreenshot;

import org.openqa.selenium.WebDriver;

 

TakesScreenshot screenshot =

        (TakesScreenshot) driver;

 

byte[] image =

        screenshot.getScreenshotAs(OutputType.BYTES);

This approach is useful for normal screenshots. For a complete page, the appropriate full-page capability or another capture strategy should be used depending on the browser and framework requirements.


6. Basic Normal Screenshot Example

import org.openqa.selenium.OutputType;

import org.openqa.selenium.TakesScreenshot;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

import java.io.File;

import java.nio.file.Files;

import java.nio.file.StandardCopyOption;

 

public class ScreenshotExample {

 

    public static void main(String[] args) throws Exception {

 

        WebDriver driver = new ChromeDriver();

 

        driver.get("https://example.com");

 

        TakesScreenshot screenshot =

                (TakesScreenshot) driver;

 

        File source =

                screenshot.getScreenshotAs(OutputType.FILE);

 

        File destination =

                new File("screenshots/homepage.png");

 

        destination.getParentFile().mkdirs();

 

        Files.copy(

                source.toPath(),

                destination.toPath(),

                StandardCopyOption.REPLACE_EXISTING

        );

 

        driver.quit();

    }

}


7. Full-Page Screenshot in Selenium 4

Selenium 4 provides APIs that can be used for full-page screenshots in supported browser implementations. A common Java approach is to use the HasFullPageScreenshot interface.

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.openqa.selenium.OutputType;

import org.openqa.selenium.HasFullPageScreenshot;

 

import java.io.File;

 

public class FullPageScreenshot {

 

    public static void main(String[] args) {

 

        WebDriver driver = new FirefoxDriver();

 

        driver.get("https://example.com");

 

        HasFullPageScreenshot fullPage =

                (HasFullPageScreenshot) driver;

 

        File screenshot =

                fullPage.getFullPageScreenshotAs(OutputType.FILE);

 

        System.out.println(

                "Screenshot saved: " + screenshot.getAbsolutePath()

        );

 

        driver.quit();

    }

}

The exact availability of a native full-page API depends on the browser driver and Selenium version being used. Always verify the capability for the target browser in the automation environment.


8. Importing HasFullPageScreenshot

When using Selenium's full-page screenshot interface in Java, the required import is:

import org.openqa.selenium.HasFullPageScreenshot;

The driver can then be cast to the interface when the selected driver supports the capability.

HasFullPageScreenshot fullPage =

        (HasFullPageScreenshot) driver;


9. Complete Full-Page Screenshot Example

import org.openqa.selenium.HasFullPageScreenshot;

import org.openqa.selenium.OutputType;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

 

import java.io.File;

import java.nio.file.Files;

import java.nio.file.StandardCopyOption;

 

public class FullPageScreenshotExample {

 

    public static void main(String[] args) throws Exception {

 

        WebDriver driver = new FirefoxDriver();

 

        try {

 

            driver.manage().window().maximize();

 

            driver.get("https://example.com");

 

            HasFullPageScreenshot fullPage =

                    (HasFullPageScreenshot) driver;

 

            File source =

                    fullPage.getFullPageScreenshotAs(

                            OutputType.FILE

                    );

 

            File destination =

                    new File(

                            "screenshots/full-page/homepage.png"

                    );

 

            destination.getParentFile().mkdirs();

 

            Files.copy(

                    source.toPath(),

                    destination.toPath(),

                    StandardCopyOption.REPLACE_EXISTING

            );

 

        } finally {

 

            driver.quit();

        }

    }

}


10. Full-Page Screenshot Using Selenium WebDriver

A full-page screenshot workflow generally consists of these steps:

  1. Start WebDriver.
  2. Navigate to the required URL.
  3. Wait for important page content to load.
  4. Ensure lazy-loaded content is handled if required.
  5. Capture the full page.
  6. Save the image.
  7. Attach the image to the test report.
  8. Close the browser.


11. Full-Page Screenshot and Long Webpages

Long webpages may contain thousands of pixels of vertical content. A viewport screenshot cannot normally display the complete page in one image.

Viewport Height

        |

        v

+-------------------+

| Section 1         |

| Section 2         |

| Section 3         |

+-------------------+

        |

        v

Remaining Page

+-------------------+

| Section 4         |

| Section 5         |

| Section 6         |

| Footer            |

+-------------------+

A full-page capture strategy combines or directly captures the content represented by both the viewport and the remaining document area.


12. JavaScript-Based Page Dimension Detection

JavaScript can be used to determine the document's complete dimensions. This is particularly useful when implementing a custom screenshot strategy.

JavascriptExecutor js =

        (JavascriptExecutor) driver;

 

Long pageHeight =

        (Long) js.executeScript(

                "return Math.max(" +

                "document.body.scrollHeight," +

                "document.documentElement.scrollHeight" +

                ");"

        );

 

System.out.println(

        "Page Height: " + pageHeight

);


13. Detecting Page Width

Long pageWidth =

        (Long) js.executeScript(

                "return Math.max(" +

                "document.body.scrollWidth," +

                "document.documentElement.scrollWidth" +

                ");"

        );

 

System.out.println(

        "Page Width: " + pageWidth

);

Page width and height can help when implementing custom capture or validation logic.


14. Scrolling the Complete Page

A custom screenshot strategy can scroll through the page and capture different viewport sections.

JavascriptExecutor js =

        (JavascriptExecutor) driver;

 

js.executeScript(

        "window.scrollTo(0, document.body.scrollHeight);"

);

After scrolling, the browser can be returned to the top:

js.executeScript(

        "window.scrollTo(0, 0);"

);


15. JavaScript Scroll-and-Capture Concept

One traditional approach for browsers without a suitable native full-page capability is to capture multiple viewport screenshots and combine them.

Determine Page Height

        |

        v

Determine Viewport Height

        |

        v

Scroll to Position 0

        |

        v

Capture Screenshot 1

        |

        v

Scroll Down

        |

        v

Capture Screenshot 2

        |

        v

Continue Until Bottom

        |

        v

Combine Images

        |

        v

Save Final Full-Page Image


16. Screenshot Stitching

Screenshot stitching means combining multiple screenshots into one larger image. This approach is useful when native full-page screenshot functionality is unavailable or when a framework requires customized capture behavior.

For example:

Image 1

+------------------+

| Header           |

| Section A        |

+------------------+

 

Image 2

+------------------+

| Section B        |

| Section C        |

+------------------+

 

Image 3

+------------------+

| Section D        |

| Footer           |

+------------------+

 

Combined Image

+------------------+

| Header           |

| Section A        |

| Section B        |

| Section C        |

| Section D        |

| Footer           |

+------------------+


17. When to Use Native Full-Page Screenshots

  • When the target browser supports the required full-page API.
  • When a complete document image is required.
  • When simplicity is important.
  • When maintaining a reusable framework utility.
  • When screenshots need to be generated consistently.


18. When to Use Custom Screenshot Logic

  • When native full-page capture is unavailable.
  • When browser-specific behavior must be controlled.
  • When screenshots need custom dimensions.
  • When stitching multiple viewport images is required.
  • When the framework needs specialized screenshot handling.


19. Full-Page Screenshot with TestNG

Full-page screenshots are particularly useful with TestNG because screenshots can be captured when tests fail.

import org.testng.annotations.Test;

 

public class ScreenshotTest {

 

    @Test

    public void verifyHomePage() {

 

        // Selenium test steps

 

        System.out.println(

                "Test executed"

        );

    }

}

A screenshot utility can be called from failure-handling logic after a test failure is detected.


20. Screenshot on Test Failure

A common automation framework requirement is to automatically capture a screenshot whenever a test fails.

Test Starts

    |

    v

Execute Test Steps

    |

    v

Test Result

    |

    +----------+

    |          |

    v          v

  PASS       FAIL

    |          |

    v          v

Continue    Capture Screenshot

               |

               v

          Save Screenshot

               |

               v

          Attach to Report


21. TestNG ITestResult

TestNG provides ITestResult, which can be used to inspect the result of a test method.

import org.testng.ITestResult;

import org.testng.annotations.AfterMethod;

 

@AfterMethod

public void afterMethod(ITestResult result) {

 

    if (result.getStatus() == ITestResult.FAILURE) {

 

        System.out.println(

                "Test failed: "

                + result.getName()

        );

 

        // Capture screenshot

    }

}


22. Screenshot Utility Class

Instead of writing screenshot logic inside every test, create a reusable utility class.

import org.openqa.selenium.OutputType;

import org.openqa.selenium.TakesScreenshot;

import org.openqa.selenium.WebDriver;

 

import java.io.File;

import java.nio.file.Files;

import java.nio.file.StandardCopyOption;

 

public class ScreenshotUtil {

 

    public static String capture(

            WebDriver driver,

            String fileName) throws Exception {

 

        TakesScreenshot screenshot =

                (TakesScreenshot) driver;

 

        File source =

                screenshot.getScreenshotAs(

                        OutputType.FILE

                );

 

        File destination =

                new File(

                        "screenshots/" + fileName + ".png"

                );

 

        destination.getParentFile().mkdirs();

 

        Files.copy(

                source.toPath(),

                destination.toPath(),

                StandardCopyOption.REPLACE_EXISTING

        );

 

        return destination.getAbsolutePath();

    }

}


23. Full-Page Screenshot Utility Design

A framework can maintain a dedicated utility for full-page screenshots.

ScreenshotUtility

        |

        +-- captureViewport()

        |

        +-- captureFullPage()

        |

        +-- captureElement()

        |

        +-- createScreenshotFolder()

        |

        +-- generateFileName()

        |

        +-- attachToReport()

This keeps screenshot functionality separate from test-case logic.


24. Full-Page Screenshot with Page Object Model

Page Object Model separates page interaction logic from test execution. Screenshot utilities can remain in a utilities package while page classes focus on application interactions.

src

|-- test

    |-- java

        |-- tests

        |   |-- LoginTest.java

        |   |-- HomePageTest.java

        |

        |-- pages

        |   |-- LoginPage.java

        |   |-- HomePage.java

        |

        |-- utilities

            |-- ScreenshotUtil.java

            |-- DriverFactory.java

            |-- WaitUtil.java


25. Full-Page Screenshot with Failure Listener

TestNG listeners can be used to centralize screenshot capture for failed tests.

import org.testng.ITestListener;

import org.testng.ITestResult;

 

public class TestListener implements ITestListener {

 

    @Override

    public void onTestFailure(

            ITestResult result) {

 

        System.out.println(

                "Test failed: "

                + result.getName()

        );

 

        // Capture screenshot using driver

    }

}

A production implementation should obtain the correct WebDriver instance associated with the current test execution.


26. Why Use a Listener?

  • Centralizes failure handling.
  • Avoids duplicate screenshot code.
  • Automatically captures failure evidence.
  • Works across multiple test classes.
  • Can integrate with reporting systems.
  • Makes the framework easier to maintain.


27. Full-Page Screenshots for Regression Testing

Regression testing often involves executing a large number of test cases after application changes. Screenshots provide visual evidence when a regression test fails.

Application Change

        |

        v

Regression Suite

        |

        v

Execute Tests

        |

        v

Failure Detected

        |

        v

Full-Page Screenshot

        |

        v

Report

        |

        v

Developer / QA Analysis


28. Full-Page Screenshot for Login Testing

Login pages can be captured after successful or failed login attempts.

Open Login Page

       |

       v

Enter Username

       |

       v

Enter Password

       |

       v

Click Login

       |

       v

Validate Result

       |

       +--------+

       |        |

       v        v

    PASS       FAIL

       |        |

       |        v

       |   Capture Screenshot

       |

       v

    Continue


29. Full-Page Screenshot for E-Commerce Testing

E-commerce pages can be very long and may contain product information, prices, reviews, recommendations, shipping details, and checkout sections.

Product Page

     |

     +-- Product Image

     |

     +-- Product Name

     |

     +-- Price

     |

     +-- Description

     |

     +-- Specifications

     |

     +-- Reviews

     |

     +-- Recommendations

     |

     +-- Footer

A full-page screenshot can provide a complete visual record of the page state.


30. Full-Page Screenshot for Forms

Long registration and checkout forms are another practical use case.

Registration Form

     |

     +-- Personal Details

     |

     +-- Contact Details

     |

     +-- Address

     |

     +-- Account Information

     |

     +-- Preferences

     |

     +-- Terms

     |

     +-- Submit Button

A full-page capture can help verify the complete layout and visible validation messages.


31. Full-Page Screenshot for Tables

Large HTML tables may extend beyond the viewport. Full-page screenshots can help capture the complete table for debugging and documentation.

+----------------------------------+

| ID | Name | Role | Status       |

+----------------------------------+

| 01 | John | Admin| Active       |

| 02 | David| User | Active       |

| 03 | Mark | User | Inactive     |

| 04 | Sara | Admin| Active       |

| ...                              |

+----------------------------------+


32. Full-Page Screenshot for Error Pages

Error pages can be captured automatically when an unexpected application state occurs.

Unexpected Error

       |

       v

Test Failure

       |

       v

Capture Full Page

       |

       v

Save Error Evidence

       |

       v

Attach to Report

       |

       v

Investigate Failure


33. Full-Page Screenshot and Dynamic Content

Dynamic websites may load content asynchronously. A screenshot taken too early may not contain the complete page.

For example:

  • Images may still be loading.
  • API data may not yet be displayed.
  • Lazy-loaded sections may not be rendered.
  • Animations may still be running.
  • Infinite-scroll content may not yet exist in the DOM.

Therefore, appropriate waits and application-specific synchronization should be used before taking a screenshot.


34. Waiting Before Full-Page Screenshot

WebDriverWait wait =

        new WebDriverWait(

                driver,

                Duration.ofSeconds(10)

        );

 

wait.until(

        ExpectedConditions.visibilityOfElementLocated(

                By.id("mainContent")

        )

);

After important content is available, the screenshot can be captured.


35. Full-Page Screenshot and Lazy Loading

Lazy-loaded content may only load when the user scrolls toward it. A full-page screenshot strategy may therefore need to trigger scrolling before capture.

JavascriptExecutor js =

        (JavascriptExecutor) driver;

 

js.executeScript(

        "window.scrollTo(0, document.body.scrollHeight);"

);

 

Thread.sleep(1000);

 

js.executeScript(

        "window.scrollTo(0, 0);"

);

For production frameworks, explicit synchronization is generally preferable to arbitrary sleep durations.


36. Full-Page Screenshot and Sticky Headers

Sticky headers remain visible while scrolling. During custom scroll-and-stitch capture, sticky elements can appear repeatedly in multiple screenshots.

Viewport 1

+----------------------+

| Sticky Header        |

| Section A            |

+----------------------+

 

Viewport 2

+----------------------+

| Sticky Header        |

| Section B            |

+----------------------+

 

Viewport 3

+----------------------+

| Sticky Header        |

| Section C            |

+----------------------+

A custom stitching implementation may need to account for fixed or sticky elements to avoid duplicate content.


37. Full-Page Screenshot and Fixed Elements

Fixed-position elements such as chat widgets, floating buttons, cookie banners, and navigation bars can affect screenshot results.

  • Cookie banners may cover content.
  • Chat widgets may appear on every viewport.
  • Sticky navigation may be repeated.
  • Floating buttons may overlap page content.

Test frameworks can optionally hide or handle these elements before screenshot capture when appropriate for the test objective.


38. Hiding an Element Before Screenshot

For controlled visual capture, JavaScript can temporarily hide an element.

JavascriptExecutor js =

        (JavascriptExecutor) driver;

 

js.executeScript(

        "document.querySelector('.chat-widget')" +

        ".style.display='none';"

);

This should only be done when hiding the element is appropriate to the purpose of the screenshot.


39. Full-Page Screenshot File Naming

Screenshot file names should be meaningful and unique.

Example:

LoginTest_admin_fullpage.png

LoginTest_invalidUser_fullpage.png

CheckoutTest_payment_fullpage.png

ProductTest_laptop_fullpage.png

Useful naming information can include:

  • Test class
  • Test method
  • Test data
  • Browser
  • Date or timestamp
  • Execution status


40. Timestamp-Based Screenshot Names

String timestamp =

        new SimpleDateFormat(

                "yyyyMMdd_HHmmss"

        ).format(new Date());

 

String fileName =

        "LoginTest_" + timestamp + ".png";

Timestamp-based naming helps prevent files from being overwritten during repeated test execution.


41. Browser-Based Screenshot Strategy

BrowserPossible Strategy
FirefoxNative full-page screenshot capability can be used when supported
Chrome/ChromiumNative or browser-specific capture mechanisms can be used depending on Selenium and driver capabilities
EdgeBrowser-specific support or custom capture may be used depending on environment
Unsupported ScenarioUse custom scrolling/stitching or another capture mechanism

Always verify the behavior against the Selenium version, browser version, and WebDriver implementation used by the project.


42. Full-Page Screenshot Using Browser Developer Protocol

Modern Chromium-based automation can use browser developer protocol functionality for advanced screenshot operations. This can be useful when a framework requires browser-specific full-page capture.

// Browser-specific CDP/BiDi screenshot logic

// can be implemented when supported

// by the Selenium version and browser.

Browser-specific APIs should be isolated inside utility classes so that the rest of the framework remains maintainable.


43. Screenshot Utility with Browser Strategy

public class ScreenshotManager {

 

    public static void captureFullPage(

            WebDriver driver,

            String fileName) {

 

        String browser =

                driver.getClass().getSimpleName();

 

        System.out.println(

                "Screenshot strategy for: "

                + browser

        );

 

        // Select appropriate strategy

        // for the current browser.

    }

}


44. Full-Page Screenshot in a Selenium Framework

A scalable automation framework can centralize screenshot handling.

Test Case

   |

   v

TestNG

   |

   v

Listener

   |

   +---- PASS ----> Continue

   |

   +---- FAIL

          |

          v

   Screenshot Manager

          |

          v

   Full-Page Capture

          |

          v

   File Storage

          |

          v

   Test Report


45. Full-Page Screenshot with Test Reports

Screenshot evidence becomes more useful when it is attached directly to test reports.

Test Execution

      |

      v

Test Result

      |

      v

Screenshot

      |

      v

Report Generator

      |

      v

HTML Report

      |

      +-- Test Name

      +-- Status

      +-- Duration

      +-- Error

      +-- Screenshot


46. Screenshot and Extent Reports

Reporting libraries such as Extent Reports can display screenshot evidence alongside test results when the framework integrates the generated image with the report.

test.fail(

        "Login test failed"

);

 

test.addScreenCaptureFromPath(

        "screenshots/login_failure.png"

);

The exact reporting API depends on the reporting library version used by the project.


47. Screenshot and Allure Reports

Allure-based frameworks can attach screenshots as test artifacts. The screenshot can be generated by Selenium and then attached to the corresponding test result.

// Conceptual flow

 

Selenium Screenshot

        |

        v

PNG File / Byte Array

        |

        v

Allure Attachment

        |

        v

Allure Test Report


48. Full-Page Screenshots in CI/CD

Full-page screenshots are valuable in continuous integration because the test may execute on a remote build server where the tester cannot directly observe the browser.

Developer Commit

       |

       v

CI Server

       |

       v

Build

       |

       v

Selenium Tests

       |

       v

Failure

       |

       v

Full-Page Screenshot

       |

       v

Artifact Storage

       |

       v

Test Report

       |

       v

QA / Developer Analysis


49. Screenshot Artifacts in Jenkins

In Jenkins-based automation, screenshots can be stored as build artifacts or exposed through test-report integrations.

Jenkins Job

    |

    +-- Source Checkout

    |

    +-- Maven Build

    |

    +-- Selenium Tests

    |

    +-- Screenshot Files

    |

    +-- Test Reports

    |

    +-- Build Artifacts


50. Full-Page Screenshot and Headless Browser

Selenium tests may execute in headless mode on CI servers. Screenshot functionality can still be used, but browser configuration and supported screenshot capabilities should be tested in the target environment.

ChromeOptions options =

        new ChromeOptions();

 

options.addArguments("--headless=new");

 

WebDriver driver =

        new ChromeDriver(options);

Headless screenshot behavior should be validated separately from headed browser execution because rendering and viewport configuration can affect the captured image.


51. Setting Browser Window Size

Consistent viewport dimensions can make screenshot comparison more predictable.

driver.manage()

        .window()

        .setSize(

                new Dimension(1440, 900)

        );

Using a consistent viewport is especially useful for visual regression testing.


52. Full-Page Screenshot and Responsive Testing

Responsive applications should be tested at multiple viewport sizes.

Desktop

1440 x 900

       |

       v

Full-Page Screenshot

 

Tablet

1024 x 768

       |

       v

Full-Page Screenshot

 

Mobile

390 x 844

       |

       v

Full-Page Screenshot

This approach helps identify responsive layout issues across different screen sizes.


53. Full-Page Screenshot for Visual Regression

Visual regression testing compares screenshots from different executions to detect unexpected UI changes.

Baseline Screenshot

        |

        v

New Test Screenshot

        |

        v

Image Comparison

        |

        +----------+

        |          |

        v          v

     Match      Difference

        |          |

        v          v

      PASS       Review

Full-page images can provide broader visual coverage, although large images may increase comparison time and storage requirements.


54. Baseline Screenshot

A baseline screenshot represents an approved visual state of an application page.

Baseline

+----------------------+

| Expected UI          |

| Header               |

| Content              |

| Footer               |

+----------------------+

 

Current

+----------------------+

| Current UI           |

| Header               |

| Content              |

| Footer               |

+----------------------+

 

Compare

       |

       v

Visual Difference


55. Screenshot Comparison Considerations

  • Use consistent browser versions.
  • Use consistent viewport sizes.
  • Use consistent zoom levels.
  • Wait for dynamic content.
  • Control animations when appropriate.
  • Handle timestamps and random content.
  • Handle advertisements and rotating content.
  • Keep test data stable.
  • Use appropriate image comparison thresholds.


56. Handling Dynamic Content Before Screenshot

Dynamic content can create false differences in visual comparison.

Examples include:

  • Current date and time.
  • Random product recommendations.
  • Rotating banners.
  • Advertisement content.
  • Live counters.
  • Animation states.
  • User-specific information.

Where appropriate, the framework can mock, freeze, hide, or otherwise stabilize dynamic content before capturing screenshots.


57. Full-Page Screenshot and Animations

Animations may cause different screenshots to be captured at different animation states.

For stable visual testing, animations can sometimes be disabled through CSS or controlled through application configuration.

JavascriptExecutor js =

        (JavascriptExecutor) driver;

 

js.executeScript(

    "document.querySelectorAll('*').forEach(" +

    "function(el) {" +

    "el.style.animation='none';" +

    "el.style.transition='none';" +

    "});"

);


58. Full-Page Screenshot for Debugging

When an automated test fails, the screenshot can help answer questions such as:

  • Was the expected page loaded?
  • Was an error message displayed?
  • Was a popup covering the page?
  • Was the application redirected?
  • Was the correct user logged in?
  • Was the page partially loaded?
  • Did a layout problem occur?


59. Screenshot on Assertion Failure

try {

 

    Assert.assertEquals(

            actualTitle,

            expectedTitle

    );

 

} catch (AssertionError error) {

 

    // Capture screenshot

 

    throw error;

}

In larger frameworks, listener-based failure handling is generally preferable because screenshot logic does not need to be repeated in every test.


60. Screenshot and Exception Handling

try {

 

    driver.findElement(

            By.id("loginButton")

    ).click();

 

} catch (Exception e) {

 

    ScreenshotUtil.capture(

            driver,

            "login_exception"

    );

 

    throw e;

}


61. Full-Page Screenshot and WebDriver Lifecycle

The browser should remain active until the screenshot has been successfully captured.

Start Driver

    |

    v

Open Page

    |

    v

Perform Test

    |

    v

Capture Screenshot

    |

    v

Save Screenshot

    |

    v

Attach Report

    |

    v

Quit Driver

If driver.quit() is executed before screenshot capture, the browser session will already be closed and the screenshot cannot be obtained from that driver.


62. Screenshot Storage Structure

A project can organize screenshots by test execution.

test-output

|-- screenshots

|   |-- LoginTest

|   |   |-- valid_login.png

|   |   |-- invalid_login.png

|   |

|   |-- SearchTest

|   |   |-- laptop_search.png

|   |   |-- mobile_search.png

|   |

|   |-- CheckoutTest

|       |-- payment_failure.png

|       |-- checkout_success.png

|

|-- reports

    |-- test-report.html


63. Screenshot Folder Creation

File folder =

        new File("screenshots");

 

if (!folder.exists()) {

    folder.mkdirs();

}

Creating the directory programmatically helps the framework work on clean CI environments where the screenshot folder does not yet exist.


64. Screenshot Naming with Test Method

String testName =

        result.getMethod().getMethodName();

 

String fileName =

        testName + "_fullpage.png";

Combining the test method name with a timestamp or unique identifier can prevent filename collisions.


65. Screenshot with Test Data

For data-driven tests, including safe test-data identifiers in screenshot names can make failures easier to locate.

loginTest_admin_fullpage.png

loginTest_manager_fullpage.png

loginTest_invalidUser_fullpage.png

Do not include passwords, tokens, API keys, or other secrets in screenshot filenames.


66. Full-Page Screenshot with Data Provider

Full-page screenshots can be combined with TestNG Data Providers.

@DataProvider(name = "users")

public Object[][] users() {

    return new Object[][] {

        {"admin"},

        {"manager"},

        {"employee"}

    };

}

 

@Test(dataProvider = "users")

public void loginTest(String username) {

 

    System.out.println(

            "Testing: " + username

    );

 

    // Perform login

    // Capture full-page screenshot if required

}


67. Full-Page Screenshot and Parallel Testing

When Data Providers or TestNG suites run in parallel, screenshot filenames must be unique. Shared screenshot utilities should also be designed to avoid race conditions.

Thread 1

   |

   +-- LoginTest_admin_001.png

 

Thread 2

   |

   +-- LoginTest_manager_002.png

 

Thread 3

   |

   +-- LoginTest_employee_003.png

Do not allow multiple parallel tests to write to the same screenshot filename.


68. Thread-Safe Screenshot Naming

String uniqueName =

        testName

        + "_"

        + Thread.currentThread().getId()

        + "_"

        + System.currentTimeMillis()

        + ".png";

This approach can help create unique names during concurrent execution.


69. Full-Page Screenshot and Remote WebDriver

When tests execute on Selenium Grid or another remote WebDriver environment, screenshot handling occurs through the remote browser session.

Test Machine

     |

     v

Selenium Grid

     |

     v

Remote Browser

     |

     v

Web Application

     |

     v

Screenshot

     |

     v

Test Machine / Report Storage

Remote execution environments should be tested to ensure the selected screenshot strategy is supported by the browser and driver configuration.


70. Full-Page Screenshot with Selenium Grid

Selenium Grid can execute tests across different browser nodes. Screenshot utilities should identify the browser and use a compatible capture strategy.

NodeBrowserScreenshot Strategy
Node 1ChromeSupported native/browser-specific strategy
Node 2FirefoxNative full-page capability when supported
Node 3EdgeCompatible browser-specific strategy


71. Full-Page Screenshot Best Practices

  • Create a reusable screenshot utility.
  • Capture screenshots automatically for failures.
  • Use meaningful file names.
  • Use unique filenames during parallel execution.
  • Store screenshots in a dedicated directory.
  • Attach screenshots to test reports.
  • Use explicit waits before capturing important pages.
  • Handle lazy-loaded content carefully.
  • Keep browser and viewport configuration consistent.
  • Do not expose sensitive information unnecessarily.
  • Keep screenshot utilities separate from test logic.
  • Verify full-page behavior on every browser used by the framework.
  • Clean old screenshots periodically in CI environments.
  • Compress or manage large image artifacts when necessary.


72. Common Mistakes in Full-Page Screenshots

  • Assuming every browser supports the same native full-page screenshot behavior.
  • Capturing the screenshot before the page has finished loading.
  • Ignoring lazy-loaded content.
  • Using duplicate filenames.
  • Closing the driver before capturing the screenshot.
  • Sharing screenshot files between parallel tests.
  • Saving screenshots in random directories.
  • Including passwords or tokens in filenames or reports.
  • Using arbitrary sleep calls instead of proper synchronization.
  • Ignoring sticky and fixed elements during custom stitching.
  • Using screenshots without attaching them to the test report.
  • Not testing screenshot functionality on CI infrastructure.


73. Full-Page Screenshot vs Element Screenshot

FeatureFull-Page ScreenshotElement Screenshot
ScopeEntire pageSpecific element
Use CaseComplete page evidenceSpecific component validation
Image SizeUsually largerUsually smaller
DebuggingPage-level issuesComponent-level issues
ExampleComplete checkout pageCheckout button


74. Full-Page Screenshot vs Viewport Screenshot

Viewport ScreenshotFull-Page Screenshot
Captures visible browser areaCaptures complete page area when supported
Smaller imageLarger image
Useful for current screen stateUseful for complete-page evidence
Simple implementationMay require browser-specific support
Good for quick failuresGood for long-page debugging


75. Full-Page Screenshot and Security

Screenshots can contain sensitive information such as usernames, email addresses, account numbers, personal information, internal URLs, or application data.

Therefore:

  • Store screenshots securely.
  • Restrict report access where necessary.
  • Do not expose credentials.
  • Avoid logging secrets.
  • Clean screenshots after the retention period.
  • Follow the organization's test-data and security policies.


76. Full-Page Screenshot and Privacy

Automation screenshots may contain real user information when testing production-like environments. Test environments should preferably use controlled or synthetic data where appropriate.


77. Full-Page Screenshot Performance Considerations

Large screenshots consume more memory and disk space than small viewport screenshots.

  • Capture only when needed.
  • Use screenshots mainly for failures when appropriate.
  • Compress image artifacts when suitable.
  • Remove outdated screenshots.
  • Avoid generating unnecessary screenshots for every test step.
  • Monitor CI storage usage.


78. Full-Page Screenshot Framework Architecture

                    Selenium Test

                          |

                          v

                     TestNG/JUnit

                          |

             +------------+------------+

             |                         |

             v                         v

         Test Logic                Listener

                                       |

                                       v

                              Screenshot Manager

                                       |

                    +------------------+------------------+

                    |                  |                  |

                    v                  v                  v

               Viewport          Full Page          Element

               Capture           Capture            Capture

                    |                  |                  |

                    +------------------+------------------+

                                       |

                                       v

                                File / Byte Data

                                       |

                                       v

                                  Test Report

                                       |

                                       v

                                  CI Artifact


79. Complete Practical Screenshot Utility

import org.openqa.selenium.OutputType;

import org.openqa.selenium.TakesScreenshot;

import org.openqa.selenium.WebDriver;

 

import java.io.File;

import java.nio.file.Files;

import java.nio.file.StandardCopyOption;

 

public class ScreenshotManager {

 

    public static String capture(

            WebDriver driver,

            String testName) throws Exception {

 

        TakesScreenshot screenshot =

                (TakesScreenshot) driver;

 

        File source =

                screenshot.getScreenshotAs(

                        OutputType.FILE

                );

 

        String fileName =

                testName

                + "_"

                + System.currentTimeMillis()

                + ".png";

 

        File destination =

                new File(

                        "test-output/screenshots/"

                        + fileName

                );

 

        destination.getParentFile().mkdirs();

 

        Files.copy(

                source.toPath(),

                destination.toPath(),

                StandardCopyOption.REPLACE_EXISTING

        );

 

        return destination.getAbsolutePath();

    }

}


80. Complete Practical TestNG Example

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.Assert;

import org.testng.ITestResult;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.Test;

 

public class ScreenshotTest {

 

    WebDriver driver;

 

    @BeforeMethod

    public void setup() {

 

        driver = new ChromeDriver();

 

        driver.manage()

                .window()

                .maximize();

 

        driver.get(

                "https://example.com"

        );

    }

 

    @Test

    public void verifyPageTitle() {

 

        String title =

                driver.getTitle();

 

        Assert.assertTrue(

                title.contains("Example")

        );

    }

 

    @AfterMethod

    public void tearDown(

            ITestResult result) throws Exception {

 

        if (result.getStatus()

                == ITestResult.FAILURE) {

 

            ScreenshotManager.capture(

                    driver,

                    result.getName()

            );

        }

 

        if (driver != null) {

            driver.quit();

        }

    }

}


81. Practical Full-Page Screenshot Project Structure

selenium-project

|

|-- src

|   |-- test

|       |-- java

|           |-- tests

|           |   |-- LoginTest.java

|           |   |-- SearchTest.java

|           |   |-- CheckoutTest.java

|           |

|           |-- pages

|           |   |-- LoginPage.java

|           |   |-- SearchPage.java

|           |   |-- CheckoutPage.java

|           |

|           |-- utilities

|           |   |-- DriverFactory.java

|           |   |-- ScreenshotManager.java

|           |   |-- WaitUtil.java

|           |

|           |-- listeners

|               |-- TestListener.java

|

|-- test-output

|   |-- screenshots

|   |-- reports

|

|-- pom.xml

|-- testng.xml


82. Real-World Screenshot Workflow

TestNG Suite

     |

     v

Login Test

     |

     v

Open Application

     |

     v

Perform Login

     |

     v

Validate Dashboard

     |

     +----------------+

     |                |

     v                v

   PASS              FAIL

     |                |

     |                v

     |        Capture Full Page

     |                |

     |                v

     |        Save Screenshot

     |                |

     |                v

     |        Attach to Report

     |                |

     +--------+-------+

              |

              v

        Test Execution End


83. Interview Questions on Full-Page Screenshots

1. What is a full-page screenshot?

A full-page screenshot captures the complete webpage rather than only the currently visible viewport.

2. Why are full-page screenshots useful in Selenium?

They provide complete visual evidence for debugging, regression testing, reporting, documentation, and failure analysis.

3. What is TakesScreenshot?

TakesScreenshot is a Selenium interface used to capture screenshots from a WebDriver session.

4. Does a normal Selenium screenshot always capture the complete webpage?

No. A normal screenshot generally represents the current browser viewport. Full-page capture requires appropriate browser support or another implementation strategy.

5. What is HasFullPageScreenshot?

HasFullPageScreenshot is a Selenium interface that exposes full-page screenshot functionality for supported WebDriver implementations.

6. Can full-page screenshots be used with TestNG?

Yes. They can be integrated with TestNG tests, listeners, configuration methods, and reporting systems.

7. Can screenshots be captured when a test fails?

Yes. TestNG listeners or configuration methods can be used to capture screenshots after a failure.

8. Why should screenshots be stored using unique names?

Unique names prevent screenshots from different tests or parallel executions from overwriting each other.

9. What is screenshot stitching?

Screenshot stitching is the process of combining multiple viewport screenshots into one larger image.

10. Why might screenshot stitching be required?

It can be used when native full-page screenshot functionality is unavailable or when custom capture behavior is required.

11. How can JavaScript help with full-page screenshots?

JavaScript can determine document dimensions, scroll through the page, trigger lazy loading, or assist in custom screenshot strategies.

12. What problems can sticky headers cause?

During custom stitching, sticky headers may appear repeatedly in multiple captured sections and require special handling.

13. Why should explicit waits be used before screenshots?

They help ensure important page elements and asynchronous content are ready before the screenshot is captured.

14. Can full-page screenshots be used in CI/CD?

Yes. They are useful as build artifacts and failure evidence in CI/CD environments.

15. Can screenshots be attached to test reports?

Yes. Many reporting frameworks support screenshot attachments.

16. Can full-page screenshots be used with Page Object Model?

Yes. Screenshot utilities can remain separate from Page Object classes while tests use both components.

17. Can full-page screenshots be used with Selenium Grid?

Yes, provided the browser, driver, Selenium version, and selected screenshot strategy support the required operation.

18. What is a major concern with screenshots containing sensitive information?

Screenshots may expose credentials, personal information, tokens, or internal application data, so they should be handled securely.

19. Why can large screenshots affect CI performance?

Large images consume additional memory, storage, upload bandwidth, and report space.

20. What is the best framework approach for screenshots?

A reusable screenshot manager combined with centralized failure handling and report integration provides a maintainable approach.


84. Quick Reference Table

ConceptPurpose
TakesScreenshotCaptures a WebDriver screenshot
HasFullPageScreenshotProvides full-page screenshot capability where supported
OutputType.FILEReturns screenshot as a file
OutputType.BYTESReturns screenshot as byte data
JavascriptExecutorCan control scrolling and inspect page dimensions
ITestResultProvides TestNG test result information
ITestListenerCentralizes TestNG execution events
Screenshot UtilityCentralizes screenshot functionality
Screenshot StitchingCombines multiple viewport images
Test ReportsDisplay test results and screenshot evidence
CI/CDStores and exposes automated test evidence


85. Learning Roadmap for Full-Page Screenshots

  1. Understand Selenium WebDriver screenshots.
  2. Learn the TakesScreenshot interface.
  3. Understand viewport screenshots.
  4. Understand full-page screenshot concepts.
  5. Learn browser-specific full-page capabilities.
  6. Learn HasFullPageScreenshot.
  7. Learn JavaScript page-dimension detection.
  8. Understand scroll-and-capture strategies.
  9. Understand screenshot stitching.
  10. Create a reusable Screenshot Utility.
  11. Integrate screenshots with TestNG.
  12. Capture screenshots after test failures.
  13. Integrate screenshots with listeners.
  14. Attach screenshots to reports.
  15. Handle screenshots in parallel execution.
  16. Handle screenshots in Selenium Grid.
  17. Integrate screenshot artifacts with CI/CD.
  18. Apply security and privacy practices.
  19. Build a complete screenshot management framework.


86. Practical Exercises

  1. Create a Selenium test that captures a normal screenshot.
  2. Create a full-page screenshot using a supported native capability.
  3. Build a reusable Screenshot Utility class.
  4. Capture a screenshot after a TestNG assertion failure.
  5. Create a TestNG listener for automatic screenshot capture.
  6. Save screenshots using unique timestamps.
  7. Capture screenshots for multiple Data Provider test cases.
  8. Implement browser-specific screenshot handling.
  9. Create a custom scroll-and-capture strategy.
  10. Attach screenshots to an HTML test report.
  11. Store screenshots as Jenkins build artifacts.
  12. Create a screenshot folder structure for a Selenium framework.
  13. Test screenshot functionality in headless mode.
  14. Test screenshots at desktop, tablet, and mobile viewport sizes.
  15. Build a complete screenshot management module using Selenium and TestNG.


87. Real-World Example: Failed Login Screenshot

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.Assert;

import org.testng.ITestResult;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.Test;

 

public class LoginScreenshotTest {

 

    WebDriver driver;

 

    @BeforeMethod

    public void setup() {

 

        driver = new ChromeDriver();

 

        driver.manage()

                .window()

                .maximize();

 

        driver.get(

                "https://example.com/login"

        );

    }

 

    @Test

    public void loginTest() {

 

        driver.findElement(

                By.id("username")

        ).sendKeys("invalidUser");

 

        driver.findElement(

                By.id("password")

        ).sendKeys("wrongPassword");

 

        driver.findElement(

                By.id("loginButton")

        ).click();

 

        String title =

                driver.getTitle();

 

        Assert.assertTrue(

                title.contains("Dashboard")

        );

    }

 

    @AfterMethod

    public void cleanup(

            ITestResult result) throws Exception {

 

        if (result.getStatus()

                == ITestResult.FAILURE) {

 

            ScreenshotManager.capture(

                    driver,

                    "failed_login"

            );

        }

 

        if (driver != null) {

            driver.quit();

        }

    }

}


88. Complete Full-Page Screenshot Architecture

                    Selenium WebDriver

                           |

                           v

                    TestNG Test Suite

                           |

                           v

                    Page Object Model

                           |

                           v

                    Application Page

                           |

                           v

                    Test Validation

                           |

              +------------+------------+

              |                         |

              v                         v

            PASS                       FAIL

              |                         |

              |                         v

              |                 Screenshot Listener

              |                         |

              |                         v

              |                 Screenshot Manager

              |                         |

              |              +----------+----------+

              |              |                     |

              |              v                     v

              |        Full-Page Capture      Viewport Capture

              |              |                     |

              +--------------+---------------------+

                             |

                             v

                       Image Storage

                             |

                             v

                        Test Report

                             |

                             v

                         CI/CD Job

                             |

                             v

                       QA / Developer


89. Summary

Full-page screenshots are an important part of modern Selenium automation frameworks. They allow testers to capture a complete webpage instead of limiting visual evidence to the current browser viewport.

Selenium provides the TakesScreenshot interface for screenshot functionality, while supported WebDriver implementations can provide full-page screenshot capabilities through appropriate APIs such as HasFullPageScreenshot.

When native full-page capture is not suitable for a particular browser or environment, automation frameworks can use browser-specific mechanisms or custom scrolling and screenshot-stitching techniques.

Full-page screenshots become especially valuable when integrated with TestNG listeners, Page Object Model, Data Providers, test reports, Selenium Grid, parallel execution, Jenkins, and CI/CD pipelines.

A professional Selenium framework should centralize screenshot functionality in a reusable utility, generate unique filenames, capture screenshots at appropriate points, attach failure evidence to reports, and protect sensitive information contained in screenshots.


90. Course Resources

Learn more about Selenium WebDriver, TestNG, automation frameworks, reporting, and practical Selenium automation:

Final Takeaway: Full-page screenshots provide complete visual evidence of web pages and are particularly useful for debugging, regression testing, failure analysis, reporting, and CI/CD automation. A well-designed Selenium framework should combine reliable screenshot capture with proper synchronization, reusable utilities, unique file naming, report integration, browser compatibility, and secure screenshot handling.

whatsapp